package cn.jinjimi.base.util;

import android.content.ContentResolver;
import android.content.Context;
import android.text.TextUtils;

import cn.jinjimi.base.R;

import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by Tony on 10/27/14.
 */
public class DateUtils {
    public static DateFormat HH_MM_DATE_FORMAT;
    public static DateFormat HH_MM_SS_DATE_FORMAT;
    public static DateFormat MM_DD_DATE_FORMAT;
    public static DateFormat MM_DD_HH_MM_DATE_FORMAT;
    public static DateFormat MM_DD_HH_MM_SS_DATE_FORMAT;
    public static DateFormat YYYY_MM_DATE_FORMAT;
    public static DateFormat YYYY_MM_DD_DATE_FORMAT;
    public static DateFormat YYYY_MM_DD_HH_MM_FORMAT;
    public static DateFormat YYYY_MM_DD_HH_MM_SS_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
    public static DateFormat TIME_24_FORMAT;
    public static SimpleDateFormat monthFormat = new SimpleDateFormat("MM", Locale.CHINA);
    public static SimpleDateFormat dayFormat = new SimpleDateFormat("dd", Locale.CHINA);
    public static SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy", Locale.CHINA);
    public static SimpleDateFormat hoursFormat = new SimpleDateFormat("HH", Locale.CHINA);


    public static String dayNames[] = {"日", "一", "二", "三", "四", "五", "六"};
    public static String monthNames[] = {"一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};

    /**
     * <pre>
     * 判断date和当前日期是否在同一周内
     * 注:
     * Calendar类提供了一个获取日期在所属年份中是第几周的方法，对于上一年末的某一天
     * 和新年初的某一天在同一周内也一样可以处理，例如2012-12-31和2013-01-01虽然在
     * 不同的年份中，但是使用此方法依然判断二者属于同一周内
     * </pre>
     *
     * @param date
     * @return
     */
    public static boolean isSameWeekWithToday(Date date) {
        if (date == null) {
            return false;
        }

        // 0.先把Date类型的对象转换Calendar类型的对象
        Calendar todayCal = Calendar.getInstance();
        Calendar dateCal = Calendar.getInstance();

        todayCal.setTime(new Date());
        dateCal.setTime(date);

        // 1.比较当前日期在年份中的周数是否相同
        return todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal
                .get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 获取时间部分 20:10
     *
     * @param date
     * @return
     */
    public static String getTime(Date date) {
        HH_MM_DATE_FORMAT = new SimpleDateFormat("HH:mm", Locale.CHINA);
        synchronized (HH_MM_DATE_FORMAT) {
            return HH_MM_DATE_FORMAT.format(date);
        }
    }

    /**
     * 本周六 20:00
     *
     * @param date
     * @return
     */
    public static String friendlyTimeOnWeek(Date date) {
        String friendTime = "";
        if (isSameWeekWithToday(date)) {
            friendTime += "本周";
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            friendTime += dayNames[dayOfWeek - 1];
            friendTime += getTime(date);
        } else {
            friendTime = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA).format(date);
        }
        return friendTime;
    }

    /**
     * 今天是否在两个时间之内
     *
     * @param begin
     * @param end
     * @return
     */
    public static boolean isBetweenWithToday(Date begin, Date end) {
        Date today = new Date();
        return today.getTime() > begin.getTime() && today.getTime() <= end.getTime();
    }

    /**
     * 返回date
     *
     * @param date
     * @return
     */
    public static Date ParseHHmmssString(String date) {
        if (StringUtils.isEmpty(date))
            return null;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        try {
            return simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    /* 返回MM月dd日 */
    public static String format(long timeMillis) {
        MM_DD_DATE_FORMAT = new SimpleDateFormat("MM月dd日", Locale.CHINA);
        Date date = new Date();
        date.setTime(timeMillis);
        return MM_DD_DATE_FORMAT.format(date);
    }

    /* 返回yyyy年MM月dd日 */
    public static String formatYYYYMMDD(long time) {
        YYYY_MM_DD_DATE_FORMAT = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);
        Date date = new Date();
        date.setTime(time);
        return YYYY_MM_DD_DATE_FORMAT.format(date);
    }

    /* 返回yyyy年MM月dd日 HH：mm */
    public static String formatYYYYMMDDHHmm(long time) {
        YYYY_MM_DD_HH_MM_FORMAT = new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.CHINA);
        Date date = new Date(time);
        return YYYY_MM_DD_HH_MM_FORMAT.format(date);
    }

    /* 返回yyyy-MM-DD HH:mm */
    public static String formatyyyymmddhhmm(long time) {
        YYYY_MM_DD_HH_MM_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        Date date = new Date(time);
        return YYYY_MM_DD_HH_MM_FORMAT.format(date);
    }

    /* 返回yyyy-MM-dd */
    public static String formatyymmdd(long time) {
        YYYY_MM_DD_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        Date date = new Date();
        date.setTime(time);
        return YYYY_MM_DD_DATE_FORMAT.format(date);
    }

    /* 返回MM-dd */
    public static String formatmmdd(long timeMillis) {
        MM_DD_DATE_FORMAT = new SimpleDateFormat("MM-dd", Locale.CHINA);
        Date date = new Date();
        date.setTime(timeMillis);
        return MM_DD_DATE_FORMAT.format(date);
    }

    /* 返回MM月 */
    public static String formatMonthCh(long time) {
        Date date = new Date();
        date.setTime(time);
        int month = Integer.valueOf(monthFormat.format(date));
        return monthNames[month - 1] + "月";
    }

    /* 返回dd */
    public static String formatdd(long time) {
        Date date = new Date();
        date.setTime(time);
        return dayFormat.format(date);
    }

    /* 返回yyyy */
    public static String formatYear(long time) {
        Date date = new Date();
        date.setTime(time);
        return yearFormat.format(date);
    }

    public static String formatMonthYear(long timeMillis) {
        Date date = new Date();
        date.setTime(timeMillis);

        if (isYesterday(timeMillis) || isToday(timeMillis)) {
            return "";
        } else {
            if (yearFormat.format(date).equals(yearFormat.format(new Date(System.currentTimeMillis()))))
                return formatMonthCh(timeMillis);
            else
                return formatMonthCh(timeMillis) + " " + formatYear(timeMillis) + "年";
        }
    }

    /* 返回HH:mm */
    public static String formatHHmm(long time) {
        Date date = new Date();
        date.setTime(time);
        return getTime(date);
    }

    /* 返回HH:mm:ss */
    public static String formatHHmmss(long timeMillis) {
        HH_MM_SS_DATE_FORMAT = new SimpleDateFormat("HH:mm:ss", Locale.CHINA);
        Date date = new Date(timeMillis);
        return HH_MM_SS_DATE_FORMAT.format(date);
    }

    public static String dealwithMomentDate(long timeMillis) {
        int minuteSeconds = 60;
        int hourSeconds = 60 * 60;
        int daySeconds = 60 * 60 * 24;
        int weekSeconds = 60 * 60 * 24 * 7;
        long todayTime = System.currentTimeMillis();
        long millisecond = todayTime - timeMillis;
        String returnText = "";

        if (millisecond > 0) {
            long seconds = millisecond / 1000;

            if (seconds <= minuteSeconds) {
                returnText = String.format("%d秒前", seconds);

            } else if (seconds < hourSeconds) {
                returnText = String.format("%d分钟前", seconds / minuteSeconds);

            } else if (seconds < daySeconds) {
                returnText = String.format("%d小时前", seconds / hourSeconds);

            } else if (seconds < weekSeconds) {
                returnText = String.format("%d天前", seconds / daySeconds);
            } else {
                returnText = formatyyyymmddhhmm(timeMillis);
            }
        } else {
            returnText = "";//未来的时间不显示
        }
        return returnText;
    }

    /**
     * 根据指定的日期和格式转换时间
     *
     * @param dataString
     * @param format
     * @return
     */
    public static long getTime(String dataString, DateFormat format) {
        long timeMillis = 0;
        try {
            timeMillis = format.parse(dataString).getTime();//毫秒
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeMillis;
    }

    /**
     * 在联系人列表中转换时间显示
     *
     * @param time
     * @param is24
     * @return
     */
    public static String dealWithDataInContact(String time, boolean is24) {
        if (time == null || TextUtils.isEmpty(time)) {
            return "";
        }
        Date targetDate;
        try {
            targetDate = YYYY_MM_DD_HH_MM_SS_FORMAT.parse(time);
        } catch (ParseException e) {
            targetDate = new Date(Long.parseLong(time));
        }

        MM_DD_DATE_FORMAT = new SimpleDateFormat("MM月dd日");
        YYYY_MM_DD_DATE_FORMAT = new SimpleDateFormat("yyyy年MM月dd日");
        if (is24) {
            HH_MM_DATE_FORMAT = new SimpleDateFormat("HH:mm");
        } else {
            HH_MM_DATE_FORMAT = new SimpleDateFormat("a hh:mm");
        }

        Date currentDate = new Date();
        if (yearFormat.format(currentDate).equals(yearFormat.format(targetDate))) {
            if (isYesterday(targetDate.getTime()))
                return "昨天";
            else {
                if (dayFormat.format(currentDate).equals(dayFormat.format(targetDate)))
                    return HH_MM_DATE_FORMAT.format(targetDate);
                else
                    return MM_DD_DATE_FORMAT.format(targetDate);
            }
        } else {
            return YYYY_MM_DD_DATE_FORMAT.format(targetDate);
        }
    }

    /**
     * 在消息中心中转换时间显示
     *
     * @param timeMillis
     * @return
     */
    public static String dealWithDataInMsg(long timeMillis, boolean is24) {
        if (is24) {
            HH_MM_DATE_FORMAT = new SimpleDateFormat("HH:mm", Locale.CHINA);
            MM_DD_HH_MM_DATE_FORMAT = new SimpleDateFormat("MM月dd日 HH:mm", Locale.CHINA);
            YYYY_MM_DD_HH_MM_FORMAT = new SimpleDateFormat("yyyy年MM月dd日 HH:mm", Locale.CHINA);
        } else {
            HH_MM_DATE_FORMAT = new SimpleDateFormat("a hh:mm", Locale.CHINA);
            MM_DD_HH_MM_DATE_FORMAT = new SimpleDateFormat("MM月dd日 a hh:mm", Locale.CHINA);
            YYYY_MM_DD_HH_MM_FORMAT = new SimpleDateFormat("yyyy年MM月dd日 a hh:mm", Locale.CHINA);
        }

        Date currentDate = new Date();
        Date targetDate = new Date(timeMillis);
        if (yearFormat.format(currentDate).equals(yearFormat.format(targetDate))) {// 年份相等
            if (isYesterday(timeMillis))
                return "昨天 " + HH_MM_DATE_FORMAT.format(targetDate);
            else {
                if (dayFormat.format(currentDate).equals(dayFormat.format(targetDate)))  // 日期相等
                    return HH_MM_DATE_FORMAT.format(targetDate);
                return MM_DD_HH_MM_DATE_FORMAT.format(targetDate);
            }
        } else {
            return YYYY_MM_DD_HH_MM_FORMAT.format(targetDate);
        }

    }

    /**
     * 客户档案显示 日 的逻辑
     *
     * @param timeMillis
     * @return
     */
    public static String dealWithDataInCustomDay(long timeMillis) {
        if (isToday(timeMillis)) {
            return "今天";
        } else if (isYesterday(timeMillis)) {
            return "昨天";
        } else
            return formatdd(timeMillis);
    }

    /**
     * 微阅读文章日期显示逻辑
     *
     * @param timeMillis
     * @return
     */
    public static String dealWithDateInArticle(Context context, long timeMillis) {
        Date currentDate = new Date();
        Date targetDate = new Date(timeMillis);
        if (yearFormat.format(currentDate).equals(yearFormat.format(targetDate))) {// 年份相等
            if (isToday(timeMillis) && System.currentTimeMillis() - timeMillis > 0) {// 今天
                TimeSpan timeSpan = new TimeSpan(targetDate, currentDate);
                if (timeSpan.hours >= 1) {
                    return MessageFormat.format(context.getString(R.string.patter_hour_aog), timeSpan.hours);
                }
                if (timeSpan.minutes >= 1) {
                    return MessageFormat.format(context.getString(R.string.patter_minute_aog), timeSpan.minutes);
                }
                return "刚刚";
            } else
                return format(timeMillis);
        } else {
            return formatYYYYMMDD(timeMillis);
        }
    }

    /**
     * 问答日期显示逻辑
     *
     * @param timeMillis
     * @return
     */
    public static String dealWithDateInQuestion(Context context, long timeMillis) {
        Date currentDate = new Date();
        Date targetDate = new Date(timeMillis);
        long currentMillis = System.currentTimeMillis();
        long dev = currentMillis - timeMillis;
        if (dev >= 0) {
            TimeSpan timeSpan = new TimeSpan(targetDate, currentDate);
            if (dev < TimeSpan.TIME_DAY_MILLIS && dev >= TimeSpan.TIME_HOUR_MILLIS) { // 1-24小时内
                return MessageFormat.format(context.getString(R.string.patter_hour_aog), timeSpan.hours);
            } else if (dev < TimeSpan.TIME_HOUR_MILLIS && dev >= TimeSpan.TIME_MINUTE_MILLIS) { //1-60分钟内
                return MessageFormat.format(context.getString(R.string.patter_minute_aog), timeSpan.minutes);
            } else if (dev < TimeSpan.TIME_MINUTE_MILLIS) {
                return "刚刚";
            } else {
                return formatyyyymmddhhmm(timeMillis);
            }
        } else {
            return formatyyyymmddhhmm(timeMillis);
        }
    }

    /* 判断当前手机是否设置为24小时制 */
    public static boolean is24HourFormat(Context context) {
        ContentResolver cv = context.getContentResolver();
        String strTimeFormat = android.provider.Settings.System.getString(cv,
                android.provider.Settings.System.TIME_12_24);

        return strTimeFormat != null && strTimeFormat.equals("24");
    }

    /* 判断是否是昨天 */
    private static boolean isYesterday(long timeMillis) {
        Calendar current = Calendar.getInstance();

        Calendar today = Calendar.getInstance();    //今天

        today.set(Calendar.YEAR, current.get(Calendar.YEAR));
        today.set(Calendar.MONTH, current.get(Calendar.MONTH));
        today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
        //  Calendar.HOUR——12小时制的小时数 Calendar.HOUR_OF_DAY——24小时制的小时数
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);

        Calendar yesterday = Calendar.getInstance();    //昨天

        yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
        yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
        yesterday.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 1);
        yesterday.set(Calendar.HOUR_OF_DAY, 0);
        yesterday.set(Calendar.MINUTE, 0);
        yesterday.set(Calendar.SECOND, 0);

        current.setTime(new Date(timeMillis));
        return (current.before(today) && current.after(yesterday));
    }

    /* 判断是否为今天 */
    public static boolean isToday(long timeMillis) {
        Date todayData = new Date();
        Date targetData = new Date(timeMillis);

        return yearFormat.format(todayData).equals(yearFormat.format(targetData)) &&
                monthFormat.format(todayData).equals(monthFormat.format(targetData)) &&
                dayFormat.format(todayData).equals(dayFormat.format(targetData));
    }

    /* 判断是否为同一天并且同一个时间段 以中午12点为分界线划分为两个时间段 */
    public static boolean isSameTimePeriod(long timeMillis) {
        Date todayData = new Date();
        Date targetData = new Date(timeMillis);

        return yearFormat.format(todayData).equals(yearFormat.format(targetData)) &&
                monthFormat.format(todayData).equals(monthFormat.format(targetData)) &&
                dayFormat.format(todayData).equals(dayFormat.format(targetData)) &&
                ((Integer.valueOf(hoursFormat.format(todayData)) < 12 &&
                        Integer.valueOf(hoursFormat.format(targetData)) < 12) ||
                        (Integer.valueOf(hoursFormat.format(todayData)) >= 12 &&
                                Integer.valueOf(hoursFormat.format(targetData)) >= 12));
    }

    /**
     * 判断两个时间戳是否为同一天
     *
     * @param timeMillis
     * @param targetTimeMillis
     * @return
     */
    public static boolean isSameDay(long timeMillis, long targetTimeMillis) {
        Date date = new Date(timeMillis);
        Date targetDate = new Date(targetTimeMillis);
        return yearFormat.format(date).equals(yearFormat.format(targetDate)) &&
                monthFormat.format(date).equals(monthFormat.format(targetDate)) &&
                dayFormat.format(date).equals(dayFormat.format(targetDate));
    }

    /**
     * 获取客户周岁数据
     *
     * @param timeMillis
     * @return
     */
    public static int getYearInTimeMillis(String timeMillis) {
        Date date = new Date(Long.valueOf(timeMillis));
        Date currentDate = new Date(System.currentTimeMillis());

        return Integer.valueOf(yearFormat.format(currentDate)) - Integer.valueOf(yearFormat.format(date));
    }

    public static String getNextMonthStr() {
        YYYY_MM_DATE_FORMAT = new SimpleDateFormat("yyyyMM", Locale.CHINA);
        Calendar current = Calendar.getInstance();
        current.add(Calendar.MONTH, 1);


        return YYYY_MM_DATE_FORMAT.format(new Date(current.getTimeInMillis()));

    }

    public static String getYearMonthBefore(int before) {
        YYYY_MM_DATE_FORMAT = new SimpleDateFormat("yyyyMM", Locale.CHINA);
        Calendar current = Calendar.getInstance();
        current.add(Calendar.MONTH, before);
        return YYYY_MM_DATE_FORMAT.format(new Date(current.getTimeInMillis()));
    }

    public static String getYearMonthAfter(String time) {
        YYYY_MM_DATE_FORMAT = new SimpleDateFormat("yyyyMM", Locale.CHINA);
        Date date = null;
        try {
            date = YYYY_MM_DATE_FORMAT.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            date = new Date();
        }
        Calendar current = Calendar.getInstance();
        current.setTime(date);
        current.add(Calendar.MONTH, 1);
        return YYYY_MM_DATE_FORMAT.format(current.getTime());
    }


    /**
     * 判断是否为合法的日期时间字符串
     *
     * @param inputData
     * @return boolean;符合为true,不符合为false
     */
    public static boolean isIllgaleDate(String inputData, String rDateFormat) {
        return isIllgaleDate(inputData, new SimpleDateFormat(rDateFormat));
    }

    public static boolean isIllgaleDate(String inputData, SimpleDateFormat simpleDateFormat) {
        if (StringUtils.isNotEmpty(inputData)) {
            simpleDateFormat.setLenient(false);
            try {
                simpleDateFormat.format(simpleDateFormat.parse(inputData));
            } catch (Exception e) {
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 转换生日
     * <p/>
     * 公历转农历
     */
    public static String gregorianToLunar(long birth) {
        Calendar date = Calendar.getInstance();
        date.setTimeInMillis(birth);
        Lunar lunar = new Lunar(date);
        return lunar.toString();
    }

    /* 时间转 00：00：00*/
    public static String formatDuration(long duration) {
        long result = duration;
        if (result <= 0)
            return "00:00";
        result /= 1000; // milliseconds into seconds
        long minute = result / 60;
        long hour = minute / 60;
        minute %= 60;
        long second = result % 60;
        if (hour != 0)
            return String.format("%02d:%02d:%02d", hour, minute, second);
        else
            return String.format("%02d:%02d", minute, second);
    }

    // 用于统计时间差
    public static class TimeSpan {

        public static final int TIME_SECOND_MILLIS = 1000;
        public static final int TIME_MINUTE_MILLIS = 60 * TIME_SECOND_MILLIS;
        public static final int TIME_HOUR_MILLIS = 60 * TIME_MINUTE_MILLIS;
        public static final int TIME_DAY_MILLIS = 24 * TIME_HOUR_MILLIS;
        public static final int TIME_WEEK_MILLIS = 7 * TIME_DAY_MILLIS;
        public static final int TIME_YEAR_MILLIS = 365 * TIME_DAY_MILLIS;

        // 相差天数
        public int days;

        // 相差小时数
        public int hours;

        // 相差分数
        public int minutes;

        // 相差秒数
        public int seconds;

        public long diff;

        public TimeSpan(Date date1, Date date2) {
            this(Math.abs(date1.getTime() - date2.getTime()));
        }

        public TimeSpan(long millisDiff){
            if(millisDiff>=0) {
                diff = millisDiff;
                days = Long.valueOf(diff / TIME_DAY_MILLIS).intValue();
                hours = Long.valueOf(diff / TIME_HOUR_MILLIS % 24).intValue();
                minutes = Long.valueOf(diff / TIME_MINUTE_MILLIS % 60).intValue();
                seconds = Long.valueOf(diff / TIME_SECOND_MILLIS % 60).intValue();
            }
        }
    }

}
